﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.Administration;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Publishing.Internal;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using System.Web;
using System.Diagnostics;

namespace Macaw.Moss2007.QuickDeployEnhancements
{
    public class QuickDeployInitiate : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        protected Repeater JobRepeater;
        protected Label errormessage;

        private DataTable jrdata;

        protected override SPBasePermissions RightsRequired
        {
            get
            {

                SPBasePermissions permissions = base.RightsRequired
                    | SPBasePermissions.EditListItems;

                return permissions;

            }
        }

        private void UpdateData()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                ContentDeploymentJobCollection cdjc = Microsoft.SharePoint.Publishing.Administration.ContentDeploymentJob.GetAllQuickDeployJobs();

                bool registerRefresh = false;

                jrdata = new DataTable();
                DataColumn jrdName = jrdata.Columns.Add("Name", typeof(string));
                DataColumn jrdIsEnabled = jrdata.Columns.Add("IsEnabled", typeof(bool));
                DataColumn jrdLastRunTime = jrdata.Columns.Add("LastRunTime", typeof(DateTime));
                DataColumn jrdLastStatusMessage = jrdata.Columns.Add("LastRunStatusMessage", typeof(string));
                DataColumn jrdId = jrdata.Columns.Add("Id", typeof(Guid));
                DataColumn jrdNextRunTime = jrdata.Columns.Add("NextRunTime", typeof(DateTime));
                DataColumn jrdQuickDeployItems = jrdata.Columns.Add("QuickDeployItems", typeof(int));
                DataColumn jrdLastStatus = jrdata.Columns.Add("LastStatus", typeof(string));

                foreach (ContentDeploymentJob job in cdjc)
                {
                    string scurl = SPUrlUtility.CombineUrl(job.Path.SourceServerUri.ToString(), job.Path.SourceSiteCollection);
                    using (SPSite site = new SPSite(scurl))
                    {
                        if (site.ID.Equals(SPContext.Current.Site.ID))
                        {
                            DataRow jrdrow = jrdata.NewRow();
                            jrdrow[jrdName] = job.Name;
                            jrdrow[jrdIsEnabled] = job.IsEnabled;
                            jrdrow[jrdLastRunTime] = job.LastRunTime;
                            jrdrow[jrdLastStatusMessage] = job.LastStatusMessage;
                            jrdrow[jrdId] = job.Id;
                            jrdrow[jrdLastStatus] = job.LastStatus.ToString();
                            jrdrow[jrdNextRunTime] = job.NextRunTime;

                            string jobid = job.Id.ToString().ToLower();
                            SPQuery query = new SPQuery();
                            query.RowLimit = 999;
                            query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + jobid + "</Value></Eq></Where>";
                            SPList qdlist = site.RootWeb.Lists["Quick Deploy Items"];
                            jrdrow[jrdQuickDeployItems] = qdlist.GetItems(query).Count;
                            jrdata.Rows.Add(jrdrow);
                        }
                    }
                }
            });
            JobRepeater.DataSource = jrdata;
            JobRepeater.DataBind();
        }

        protected override void CreateChildControls()
        {
            errormessage.Text = null;

            UpdateData();

            base.CreateChildControls();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        private SPGroup GetQuickDeployUsersGroup()
        {
            SPGroup qdugroup = null;
            try
            {
                qdugroup = SPContext.Current.Site.RootWeb.Groups["Quick Deploy Users"];
            }
            catch
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    EventLog.WriteEntry(this.GetType().FullName, "Unable to retrieve the Quick Deploy group", EventLogEntryType.Warning);
                });
            }
            return qdugroup;
        }

        protected void Start_Click(object sender, EventArgs e)
        {
            EnsureChildControls();

            SPGroup qdugroup = GetQuickDeployUsersGroup();
            if (qdugroup == null || !qdugroup.ContainsCurrentUser)
            {
                errormessage.Text = "You are not part of the Quick Deploy Users group. Please ask your Site Administrator to make you member of this group.";
                return;
            }


            Button btn = sender as Button;
            if (btn != null)
            {
                RepeaterItem repitm = btn.Parent as RepeaterItem;
                if (repitm != null)
                {
                    try
                    {
                        #region Get a reference to the specific QuickDeploy Job
                        DataRow jrrow = jrdata.Rows[repitm.ItemIndex];
                        Guid jobguid = (Guid)jrrow["Id"];

                        #endregion

                        #region Run the QuickDeploy Job
                        // Fiddle with the FormDigestSettings to prevent "The security validation for this page is invalid." exception

                        object o = HttpContext.Current.Items["HttpHandlerSPRequestContext"];


                        try
                        {
                            SPSecurity.RunWithElevatedPrivileges(delegate
                            {
                                HttpContext.Current.Items["HttpHandlerSPRequestContext"] = null;

                                HttpContext.Current.Items["FormDigestValidated"] = true;
                                SPContext.Current.Site.WebApplication.FormDigestSettings.Enabled = false;


                                ContentDeploymentJob job = Microsoft.SharePoint.Publishing.Administration.ContentDeploymentJob.GetInstance(jobguid);

                                job.Run(true);
                            });
                        }
                        finally
                        {
                            HttpContext.Current.Items["HttpHandlerSPRequestContext"] = o;
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        errormessage.Text = "An error occured:" + ex.Message;
                    }

                    UpdateData();
                }
            }
        }

        protected void Clear_Click(object sender, EventArgs e)
        {
            EnsureChildControls();

            SPGroup qdugroup = GetQuickDeployUsersGroup();
            if (qdugroup == null || !qdugroup.ContainsCurrentUser)
            {
                errormessage.Text = "You are not part of the Quick Deploy Users group. Please ask your Site Administrator to make you member of this group.";
                return;
            }

            Button btn = sender as Button;
            if (btn != null)
            {
                RepeaterItem repitm = btn.Parent as RepeaterItem;
                if (repitm != null)
                {
                    try
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate
                        {
                            #region Get a reference to the specific QuickDeploy Job
                            DataRow jrrow = jrdata.Rows[repitm.ItemIndex];
                            Guid jobguid = (Guid)jrrow["Id"];

                            ContentDeploymentJob job = Microsoft.SharePoint.Publishing.Administration.ContentDeploymentJob.GetInstance(jobguid);
                            #endregion

                            #region Delete all QuickDeployObjects from the QuickDeploy List for this Job
                            string scurl = SPUrlUtility.CombineUrl(job.Path.SourceServerUri.ToString(), job.Path.SourceSiteCollection);
                            using (SPSite site = new SPSite(scurl))
                            {
                                SPList qdlist = site.RootWeb.Lists["Quick Deploy Items"];

                                StringBuilder sbDelete = new StringBuilder();
                                sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                                string command = "<Method><SetList Scope=\"Request\">" + qdlist.ID +
                                "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";

                                foreach (SPListItem item in qdlist.Items)
                                {
                                    string titleguid = item.Title.ToLower();
                                    if (titleguid.Equals(job.Id.ToString().ToLower(), StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        sbDelete.Append(string.Format(command, item.ID.ToString()));
                                    }
                                }

                                sbDelete.Append("</Batch>");

                                site.RootWeb.AllowUnsafeUpdates = true;
                                try
                                {
                                    site.RootWeb.ProcessBatchData(sbDelete.ToString());
                                }
                                finally
                                {
                                    site.RootWeb.AllowUnsafeUpdates = false;
                                }
                            }
                            #endregion
                        });
                    }
                    catch (Exception ex)
                    {
                        errormessage.Text = "An error occured:" + ex.Message;
                        SPSecurity.RunWithElevatedPrivileges(delegate
                        {
                            EventLog.WriteEntry(this.GetType().FullName, "Error occurred deleting Quick Deploy Objects\r\n" + ex.ToString(), EventLogEntryType.Warning);
                        });
                    }
                    UpdateData();
                }
            }
        }


    }
}
